/***************************************** 
 * Desc: UGUI公用工具方法
*****************************************/
using Common.UGUI.Base.Data;
using UnityEngine;

namespace Common.UGUI.Helper {

	public sealed class UGUICommonHelper {

		private static UGUIBaseData _uguiBaseData = null;

		/// <summary>
		/// 世界坐标到屏幕坐标的转换函数
		/// </summary>
		/// <param name="worldPos">当前世界坐标</param>
		/// <param name="currentCam">当前摄像机</param>
		/// <returns></returns>
		public static Vector3 WorldToCurrentResolutionPosition(Vector3 worldPos, Camera currentCam) {

			//if(_uguiBaseData == null) {
			//	_uguiBaseData = UGUIModule.Instance.UGUIBaseData;
			//}

			if (_uguiBaseData != null) {

				Vector3 screenPos = currentCam.WorldToScreenPoint(worldPos);

				float resolutionX = _uguiBaseData.ResolutionX;
				float resolutionY = _uguiBaseData.ResolutionY;

				screenPos.x = screenPos.x * resolutionX / Screen.width;
				screenPos.y = screenPos.y * resolutionY / Screen.height;

				return screenPos;

			} else {

				Debug.LogError("WorldToCurrentResolutionPosition called failed: UGUIBaseData is null, you need init UGUIModule first.");

				return Vector2.zero;
            }
		}

		/// <summary>
		/// 根据实际屏幕尺寸和逻辑尺寸换算当前实际屏幕尺寸下UI的位置(默认以宽为基准)
		/// </summary>
		public static Vector3 ConvertUIPosByLogicResolution(Vector3 uiPos, Vector2 screenRes) {

			//if (_uguiBaseData == null) {
			//	_uguiBaseData = UGUIModule.Instance.UGUIBaseData;
			//}

			if (_uguiBaseData != null) {

				float resolutionX = _uguiBaseData.ResolutionX;
				float resolutionY = _uguiBaseData.ResolutionY;

				float logic_wh_Ratio = resolutionY / resolutionX;
				float screen_wh_Ratio = screenRes.y / screenRes.x;

				uiPos.x = uiPos.x * resolutionX / screenRes.x;
				uiPos.y = uiPos.y * resolutionY / screenRes.y;

				uiPos.y = uiPos.y * screen_wh_Ratio / logic_wh_Ratio;

				return uiPos;

			} else {

				Debug.LogError("WorldToCurrentResolutionPosition called failed: UGUIBaseData is null, you need init UGUIModule first.");

				return Vector2.zero;
			}
		}

		/// <summary>
		/// 根据实际屏幕尺寸和逻辑尺寸换算当前实际屏幕尺寸下UI的位置
		/// </summary>
		public static Vector3 ConvertUIPosByLogicResolution(Vector3 uiPos) {

			return ConvertUIPosByLogicResolution(uiPos, new Vector2(Screen.width, Screen.height)); ;
		}
	}
}
